'use strict';

import Toast from 'react-native-root-toast';
import config from '../../../config';
import { NetInfo, DeviceEventEmitter } from 'react-native';
import { Utils, Storage } from '../';
import { baseParams as baseQuery } from '../../wedgets/BaseComponent';

class RequestError {
  constructor(code, object, description) {
    this.code = code;
    this.object = object;
    this.description = description;
  }
}

export default class Fetch {
  constructor({
    url = '',
    method = 'get',
    headers = {},
    timeout = 12000,
    data = {},//post请求传递data
    params = {}//get请求传params
  }) {
    Object.assign(this, {
      url: `${config.host||''}${url}`,
      method: method.toUpperCase(),
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
        ...headers
      },
      data,
      timeout,
      show_error: true,
      params
    });
  }

  async dofetch() {
    const { method, headers, data, params, url, timeout } = this;
    const options = {
      method,
      headers,
      credentials: 'same-origin',
      dataType: 'json',
      timeout
    };
    const __shop_id = await Storage.getData('shop_id');
    let tempQuery = {
      // ...baseQuery,
      ...params,
      // __shop_id
    };
    
    if (method === 'POST') {
      options.body = JSON.stringify(data);
    } else {
      tempQuery = {
        // ...tempQuery,
        ...data
      };
    }
    // console.log('OOOOOOOOOOOOOO',`${url}${Utils.object2query(tempQuery)}`);
    return Promise.race([
      //正常请求
      fetch(`${url}${Utils.object2query(tempQuery)}`, options),
      //检查是否超时
      // new Promise((_, reject) => {
      //   setTimeout(() => reject(new Error('request timeout')), timeout);
      // }),
      //检查是否断网,延时为了解决IOS问题
      new Promise((_, reject) => {
        NetInfo.isConnected.fetch().done(isConnected => {
          if (!isConnected) {
            reject(new Error('noNetwork'));
          }
        });
      })
    ])
      .then(res => res.json())
      .then((res = {}) => {
        //处理服务器错误
        if (res.status === 'error') {
          const { error_msg = '', error_code = '' } = res.result || {};
          //登录失效
          console.log(`-- fetch error: request ${url} failed --`, error_msg);

          if (
            error_msg === '未知授权UUID' ||
            error_msg === '无效的用户信息' ||
            error_code == 6001
          ) {
            try {
              Storage.deleteData('uuid');
            } catch (error) {
              console.log(error)
            }
            
            DeviceEventEmitter.emit('unlogin');
            Toast.show('请登录~');
          } else {
            if (error_msg) Toast.show(error_msg);
          }

          return Promise.reject(
            new RequestError('500', res.errorObject, '服务器代码执行错误')
          );
        }

        return res;
      })
      .catch(error => {
        console.log(`-- request server error: ${url} --`, error);
        /**
         * 此处处理非后台异常，如网络异常等
         * 将异常抛出由页面实施者根据实际需要处理
         *  */
        if (this.show_error == true && error.message == 'noNetwork') {
          Toast.show('网络连接异常，请检查网络设置');
        } else if (this.show_error == true && error.message == 'timeout') {
          Toast.show('网络连接超时');
        }

        throw error;
      });
  }
}
